package com.thinkingcoder.tcrpc.core.router;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.thinkingcoder.tcrpc.core.meta.InstanceMeta;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 可以做一些灰度用户，某一次请求标记上加上灰度标记<br/>
 * 可以结合蓝绿<br/>
 * grayRatio=0 都是 normal<br/>
 * grayRatio=100 都是 gray
 * 
 */
@Slf4j
@Data
public class GrayRouter implements Router<InstanceMeta> {

    private int grayRatio;

    private final Random random = new Random();

    public GrayRouter(int grayRatio) {
        this.grayRatio = grayRatio;
    }

    @Override
    public List<InstanceMeta> route(List<InstanceMeta> providers) {

        if (providers == null || providers.size() <= 1) {
            return providers;
        }

        List<InstanceMeta> normalNodes = new ArrayList<>();
        List<InstanceMeta> grayNodes = new ArrayList<>();

        providers.forEach(node -> {
            if ("true".equalsIgnoreCase(node.getParameters().get("gray"))) {
                grayNodes.add(node);
            } else {
                normalNodes.add(node);
            }
        });

        log.debug(" grayRouter grayNodes/normalNodes,grayRatio ===> {}/{},{}", grayNodes.size(), normalNodes.size(),
            grayRatio);

        if (normalNodes.isEmpty() || grayNodes.isEmpty()) {
            return providers;
        }

        if (grayRatio <= 0) {
            return normalNodes;
        } else if (grayRatio >= 100) {
            return grayNodes;
        }

        if (random.nextInt(100) <= grayRatio) {
            log.debug(" grayRouter grayNodes ===> {} ", grayNodes);
            return grayNodes;
        } else {
            log.debug(" grayRouter normalNodes ===> {} ", normalNodes);
            return normalNodes;
        }

    }
}
